package cn.szzsi._admin;

import cn.szzsi.common.excel.ExcelReader;
import cn.szzsi.common.kit.WeixinUtil;
import cn.szzsi.core.kit.UtilDate;
import cn.szzsi.service.MemberService;
import cn.szzsi.common.excel.PoiRender;
import cn.szzsi.common.kit.CommonUtil;

import cn.szzsi.common.model.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.JFinal;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.render.Render;
import com.jfinal.upload.UploadFile;
import org.apache.commons.collections.map.HashedMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by admin on 2017/7/31.
 */
public class BrandMemberController extends BaseAdminController<Member> {
    public static  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
    private String shopId;
    public void list(){
        render("member_list.html");
    }

    public void ajaxlist(){
        shopId=getAttr("shopId");
        String sourceType=getPara("sourceType");
        String sql="select * from mall_member m where 1=1 ";
        if(StrKit.notBlank(sourceType)){
            sql+=" and m.sourceType="+sourceType+"";
        }
        String province=getPara("province");
        if(StrKit.notBlank(province)&& !"全部".equals(province)){
            sql +=" and m.province='"+province+"'";
        }
        String city=getPara("city");
        if(StrKit.notBlank(city)&&!"全部".equals(city)){
            sql +=" and m.city='"+city+"'";
        }
        String district=getPara("district");
        if(StrKit.notBlank(district)&&!"全部".equals(district)&&!"市辖区".equals(district)){
            sql +=" and m.district='"+district+"'";
        }
        String name=getPara("name");
        if(StrKit.notBlank(name)){
            sql +=" and (m.phone like '%"+name+"%' or m.realname like'%"+name+"%' or m.username like'%"+name+"%')";
        }

        String startname=getPara("starttime");
        if(StrKit.notBlank(startname)){
            sql+=" and m.createDate>='"+startname+"'";
        }
        String endtime=getPara("endtime");
        if(StrKit.notBlank(endtime)){
            sql+=" and m.createDate<='"+endtime+"'";
        }
        sql+=" and m.shopId='"+shopId+"' order by m.createDate desc";
        List<Member> lm = Member.dao.find(sql);
        renderJson(lm);
    }

    /**
     * 品牌会员导入引导
     */
    public void importBrandMember(){
        render("import_brand_member.html");
    }
    /**
     * 导入品牌会员示例
     */
    public void brandMemberDemo(){
        List list=new ArrayList();
        Map<String,Object> map=new HashedMap();
        map.put("phone","13800000000");
        map.put("realname","张三");
        map.put("province","江苏省");
        map.put("city","苏州市");
        map.put("createDate","2017-04-01 15:38:08");
        map.put("birthday","1991-04-01 00:00:00");
        list.add(map);
        String[] header={"手机号","姓名","所在省","所在市","入会时间","生日"};
        String[] columns={"phone","realname","province","city","createDate","birthday"};
        Render poirender = PoiRender.me(list).fileName("member.xls").headers(header).sheetName("member").columns(columns);
        render(poirender);
    }
    /**
     * 导入品牌会员
     */
    @Before(Tx.class)
    public void importBrandMemberData(){
        shopId=getAttr("shopId");
        UploadFile uploadFile = getFile("memberFile");
        File filExcel = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());//默认文件路径
        ExcelReader excelReader=new ExcelReader();//new 一个对象
        try {
            InputStream is = new FileInputStream(filExcel);
            Map<Integer, List> map = excelReader.readExcelContent(is);
            MemberRank memberRank=MemberRank.dao.getDefaultMemberRank(shopId);
            String memberRankId="";
            if(memberRank!=null){
                memberRankId=memberRank.getId();
            }
            for(int i=1;i<=map.size();i++){//多少行
                Member member=new Member();
                List<String> list=map.get(i);
                for(int j=0;j<list.size();j++){//取出每行的数据
                    if(StrKit.isBlank(list.get(0))){
                        renderJson(Ret.fail("info","导入失败,第"+(i+1)+"行手机号不允许为空!"));
                        return;
                    }
                    if(StrKit.isBlank(list.get(4))){
                        renderJson(Ret.fail("info","导入失败,第"+(i+1)+"入会时间不允许为空!"));
                        return;
                    }
                    if(j==0){
                        member.setPhone(list.get(0));
                    }
                    if(j==1){
                        member.setRealname(list.get(1));
                        member.setUsername(list.get(1));
                    }
                    if(j==2){
                        member.setProvince(list.get(2));
                    }
                    if(j==3){
                        member.setCity(list.get(3));
                    }
                    if(j==4){
                        member.set("createDate",list.get(4));
                    }
                    if(j==5){
                        member.set("birthday",list.get(5));
                    }

                }
                member.setId(StrKit.getRandomUUID());
                member.setShopId(shopId);
                member.setSourceType("1");
                member.setModifyDate(new Date());
                member.setPassword("e10adc3949ba59abbe56e057f20f883e");
                member.setMemberRankId(memberRankId);
                member.save();
            }
            filExcel.delete();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        renderJson(Ret.ok());

    }


    /**
     * 潜在用户导入引导
     */
    public void importpotentialMember(){
        render("import_ potential_member.html");
    }
    /**
     * 导入潜在用户会员示例
     */
    public void potentialMemberDemo(){
        List list=new ArrayList();
        Map<String,Object> map=new HashedMap();
        map.put("phone","13800000000");
        map.put("createDate","2017-04-01 15:38:08");
        list.add(map);
        String[] header={"手机号","入会时间"};
        String[] columns={"phone","createDate"};
        Render poirender = PoiRender.me(list).fileName("member.xls").headers(header).sheetName("member").columns(columns);
        render(poirender);
    }

    /**
     * 导入品牌会员
     */
    @Before(Tx.class)
    public void importPotentialMemberData(){
        shopId=getAttr("shopId");
        UploadFile uploadFile = getFile("memberFile");
        File filExcel = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());//默认文件路径
        ExcelReader excelReader=new ExcelReader();//new 一个对象
        try {
            InputStream is = new FileInputStream(filExcel);
            Map<Integer, List> map = excelReader.readExcelContent(is);
            for(int i=1;i<=map.size();i++){//多少行
                Member member=new Member();
                List<String> list=map.get(i);
                for(int j=0;j<list.size();j++){//取出每行的数据
                    if(StrKit.isBlank(list.get(0))){
                        renderJson(Ret.fail("info","导入失败,第"+(i+1)+"行手机号不允许为空!"));
                        return;
                    }
                    if(StrKit.isBlank(list.get(1))){
                        renderJson(Ret.fail("info","导入失败,第"+(i+1)+"入会时间不允许为空!"));
                        return;
                    }
                    if(j==0){
                        member.setPhone(list.get(0));
                        member.setUsername(list.get(0));
                    }
                    if(j==1){
                        member.set("createDate",list.get(1));
                    }

                }
                member.setId(StrKit.getRandomUUID());
                member.setShopId(shopId);
                member.setSourceType("3");
                member.setModifyDate(new Date());
                member.setPassword("e10adc3949ba59abbe56e057f20f883e");
                member.save();
            }
            filExcel.delete();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        renderJson(Ret.ok());

    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }

    /**
     * 同步微信公众号的粉丝
     */
    public void getFansFromWeixin(){
        System.out.println("1212121212121");
        Long start=System.currentTimeMillis();
        shopId=getAttr("shopId");
        //String access_token=CommonUtil.getAccessToken(shopId);
        String access_token= WeixinUtil.getAccessToken(shopId);

        //获取openid数组
        String next_openid="";
        String openidUrl="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid+"";
        String openidResult= HttpKit.get(openidUrl);
        JSONObject jo= JSON.parseObject(openidResult);
        Integer total=Integer.valueOf(jo.get("total").toString());//关注该公众账号的总用户数
        Integer count=Integer.valueOf(jo.get("count").toString());//拉取的OPENID个数，最大值为10000
        String openids=jo.getJSONObject("data").get("openid").toString();//["oJTHKwErSUPI376-Qlt3SZyLf7L0", "oJTHKwCgv9v0Gv1P3BZ55WUD3tpM"]
        if(count>0){//拉取的用户数大于0
            openids=openids.substring(1,openids.length()-1).replace("\"","");
            String openidArr[]=openids.split(",");
            List<String> openidList= Arrays.asList(openidArr);
            for( int i=0;i<openidList.size();i++){
                String openid=openidList.get(i);
                String userInfo="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN ";
                String userInfoResult= HttpKit.get(userInfo);
                JSONObject userInfoObj=JSON.parseObject(userInfoResult);
                final String uopenid=userInfoObj.get("openid").toString();
                if(Member.dao.getByOpenid(uopenid)==null){
                    final String nickname = userInfoObj.get("nickname").toString();
                    final String sex = userInfoObj.get("sex").toString();
                    final String country = userInfoObj.get("country").toString();
                    final String province = userInfoObj.get("province").toString();
                    final String city = userInfoObj.get("city").toString();
                    final String headimgurl = userInfoObj.get("headimgurl").toString();
                    Long subscribe_time=Long.valueOf(userInfoObj.get("subscribe_time").toString());
                    final String date= UtilDate.timestampToDateStr(subscribe_time*1000);
                    fixedThreadPool.execute(new Runnable() {
                        public void run() {
                            try {
                                MemberService.service.saveMemberInfo("0","0",uopenid,nickname,sex,country,province,city,headimgurl,"","",shopId,"","",date,2,"2");
                            }catch (Exception e){
                                MemberService.service.saveMemberInfo("0","0",uopenid,"",sex,country,province,city,headimgurl,"","",shopId,"","",date,2,"2");
                            }

                        }
                    });


                }

            }
            next_openid=jo.get("next_openid").toString();//上一次的最后一个openid
            Integer n=total/count;//调n次接口
            if(total>10000){
                for (int i=0;i<n;n++){
                    openidUrl="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid+"";
                    openidResult= HttpKit.get(openidUrl);
                    jo=JSON.parseObject(openidResult);
                    openids=jo.getJSONObject("data").get("openid").toString();//["oJTHKwErSUPI376-Qlt3SZyLf7L0", "oJTHKwCgv9v0Gv1P3BZ55WUD3tpM"]
                    openids=openids.substring(1,openids.length()-1).replace("\"","");
                    openidArr=openids.split(",");
                    openidList=Arrays.asList(openidArr);
                    for( int j=0;j<openidList.size();j++){
                        String openid=openidList.get(i);
                        String userInfo="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN ";
                        String userInfoResult= HttpKit.get(userInfo);
                        JSONObject userInfoObj=JSON.parseObject(userInfoResult);
                        final String uopenid=userInfoObj.get("openid").toString();
                        if(Member.dao.getByOpenid(uopenid)==null){
                            final String nickname = userInfoObj.get("nickname").toString();
                            final String sex = userInfoObj.get("sex").toString();
                            final String country = userInfoObj.get("country").toString();
                            final String province = userInfoObj.get("province").toString();
                            final String city = userInfoObj.get("city").toString();
                            final String headimgurl = userInfoObj.get("headimgurl").toString();
                            Long subscribe_time=Long.valueOf(userInfoObj.get("subscribe_time").toString());
                            final String date=UtilDate.timestampToDateStr(subscribe_time*1000);

                            fixedThreadPool.execute(new Runnable() {
                                public void run() {
                                    try {
                                        MemberService.service.saveMemberInfo("0","0",uopenid,nickname,sex,country,province,city,headimgurl,"","",shopId,"","",date,2,"2");
                                    }catch (Exception e){
                                        MemberService.service.saveMemberInfo("0","0",uopenid,"",sex,country,province,city,headimgurl,"","",shopId,"","",date,2,"2");
                                    }

                                }
                            });

                        }

                    }
                }
            }


        }
        Long end=System.currentTimeMillis();
        System.out.println("时间----------------------"+(end-start)/1000);

        renderJson(Ret.ok("info","操作成功!"));

    }

    /**
     * 会员详情
     */
    public void memberDetail(){
        String memberId=getPara("memberId");
        String sourceType=getPara("sourceType");
        System.out.println(memberId);
        Member member=Member.dao.findById(memberId);
        setAttr("member",member);
        if("1".equals(sourceType)){
            render("member_detail_brand.html");
        }else if("2".equals(sourceType)){
            render("member_detail_wx.html");
        }else if("3".equals(sourceType)){
            render("member_detail_potential.html");
        }

    }

    /**
     * 行为日志
     */
    public void ajaxmemberlog(){
        String sql="select * from mall_member_action_log order by createDate desc";
        List<MemberActionLog> lma=MemberActionLog.dao.find(sql);
        renderJson(lma);
    }

    public void memberstatics(){
        shopId=getAttr("shopId");
        Record memberCount= Db.findFirst("select count(*) memberCount from mall_member where shopId=?",shopId);
        setAttr("memberCounts",memberCount.getLong("memberCount"));
        render("member_statics.html");
    }

}
